package validator;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import ognl.OgnlException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * TODO
 * Jakarta Commons 项目Validator
 * sping对数据的验证http://jinnianshilongnian.iteye.com/blog/1733708
 * 打包自定义方法js
 * @author heantai
 *
 */
public class JqueryValidator {
	
	private static final Logger log=LoggerFactory.getLogger(JqueryValidator.class);
	
	public final static String ERR_MSGS="ERR_MSGS";
	
	private final static String FIELDS="rules";
	
	private final static String MESSAGES="messages";

	
	/**
	 * 
	 * @param validator
	 * @return	格式为
	 * 				rules:{'name':{maxlength:10,required:true}},messages:{'name':{maxlength:'输入10个字符'}}
	 */
	public static String toJson(Map<String, Map<String,Map<String, String>>> validator){
		Map<String, Map<String, String>> fieldsMap=validator.get(FIELDS);
		Iterator<String> iterator =fieldsMap.keySet().iterator();
		//rules:{'name':{maxlength:10,required:true}},messages:{'name':{maxlength:'输入10个字符'}}
		StringBuilder sb=new StringBuilder(FIELDS).append(":{");//rules:{
		while(iterator.hasNext()){//域迭代
			String field=iterator.next();
			sb.append("'").append(field).append("':{");//'name':{
			
			Iterator<String> rules=fieldsMap.get(field).keySet().iterator();
			Map<String, String> rulesMap=fieldsMap.get(field);
			while(rules.hasNext()){//域规则验证
				String rule=rules.next();
				//maxlength:10,
				sb.append(rule).append(":");
				if(JqueryMethod.EQUALTO.equals(rule)||JqueryMethod.ACCEPT.equals(rule)){
					sb.append("'").append(rulesMap.get(rule)).append("'");
				}else{
					sb.append(rulesMap.get(rule));
				}
				sb.append(",");
			}
			sb.deleteCharAt(sb.length()-1);
			
			sb.append("},");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("},").append(MESSAGES).append(":{");
		
		Map<String, Map<String, String>> messagesMap=validator.get(MESSAGES);
		iterator =messagesMap.keySet().iterator();
		while(iterator.hasNext()){//域迭代
			String field=iterator.next();
			sb.append("'").append(field).append("':{");//'name':{
			
			Iterator<String> rules=messagesMap.get(field).keySet().iterator();
			Map<String, String> rulesMap=messagesMap.get(field);
			while(rules.hasNext()){//域规则验证
				String rule=rules.next();
				//maxlength:'输入10个字符',
				sb.append(rule).append(":");
				sb.append("'").append(rulesMap.get(rule)).append("'").append(",");
			}
			sb.deleteCharAt(sb.length()-1);
			
			sb.append("},");
		}
		sb.deleteCharAt(sb.length()-1);
		sb.append("}");
		
		return sb.toString();
	}
	
	public static String map2Json(Map<String, String> map){
		if(map==null||map.isEmpty()){
			return "";
		}
		
		StringBuilder sb=new StringBuilder();
		Iterator<String> iterator=map.keySet().iterator();
		while(iterator.hasNext()){
			String key=iterator.next();
			sb.append("'").append(key).append("':'").append(map.get(key)).append("',");
		}
		
		return sb.deleteCharAt(sb.length()-1).toString();
	}
	
	public static Map<String, Map<String,Map<String, String>>> initValidatorMap(){
		Map<String, Map<String,Map<String, String>>> map=new HashMap<String, Map<String,Map<String,String>>>();
		map.put(FIELDS, new HashMap<String, Map<String,String>>());
		map.put(MESSAGES, new HashMap<String, Map<String,String>>());
		return map;
	}
	
	/**
	 * 
	 * 前端及后台的验证顺序为规则的设置顺序（前端required验证顺序除外）
	 * @param validator
	 * @param field
	 * @param rule
	 * @param ruleValue
	 * @param message
	 * @return
	 */
	public static Map<String, Map<String,Map<String, String>>> setFieldValidate(Map<String, Map<String,Map<String, String>>> validator,
			String field,String rule,String ruleValue,String message){
		if(rule!=null){
			Map<String, String> fieldMap=validator.get(FIELDS).get(field);
			if(fieldMap==null){
				fieldMap=new LinkedHashMap<String, String>();//验证时按照规则的设置顺序进行验证
				validator.get(FIELDS).put(field, fieldMap);
			}
			
			fieldMap.put(rule, ruleValue);
		}
		
		
		Map<String, String> fieldMap=validator.get(MESSAGES).get(field);
		if(fieldMap==null){
			fieldMap=new HashMap<String, String>();
			validator.get(MESSAGES).put(field, fieldMap);
		}
		if(message!=null){
			message=formatMsg(ruleValue,message);
		}else{
			message=formatMsg(ruleValue,JqueryMethod.getMsg(rule));
		}
		fieldMap.put(rule, message);
		
		return validator;
	}

	/**
	 * 格式化消息
	 * @param ruleValue
	 * @param message
	 * @return
	 */
	private static String formatMsg(String ruleValue, String message) {
		if(!message.contains("{")){
			return message;
		}
		
		if(ruleValue.contains("[")){//多个参数
			String[] ruleVals=ruleValue.replace("[", "").replace("]", "").split(",");
			for (int i = 0; i < ruleVals.length; i++) {
				message=message.replace("{"+i+"}", ruleVals[i]);
				//message=message.replaceFirst("\\{\\}", "");//使用{}为占位符时使用此方法
			}
		}else{
			message=message.replace("{0}", ruleValue);
		}
		
		return message;
	}

	public static void main(String[] args) throws OgnlException {
		
		
		Map<String, Map<String,Map<String, String>>> map=initValidatorMap();
		JqueryValidator.setFieldValidate(map, "name", JqueryMethod.REQUIED, Boolean.TRUE.toString(), "请输入名字");
		JqueryValidator.setFieldValidate(map, "name", JqueryMethod.MAXLENGTH, "10", "最多输入10个字条");
		JqueryValidator.setFieldValidate(map, "name", JqueryMethod.ACCEPT, "jpg|txt", "only jpg");
		
		System.out.println(toJson(map));
		
		
		Map<String, String> m=new HashMap<String, String>();
		m.put("s", "x");
		m.put("c", "d");
//		System.out.println(toJson(m));
		
	}
	
	
	/**
	 * return 消息返回到页面，由js处理显示
	 */
	public static Map<String, String> validate(Map<String, Map<String, Map<String, String>>> validator,
			HttpServletRequest request) {
		Map<String, String> result=new HashMap<String, String>();
		Map<String, Map<String, String>> fieldsMap=validator.get(FIELDS);
		Map<String, Map<String, String>> messagesMap=validator.get(MESSAGES);
		Iterator<String> iterator =fieldsMap.keySet().iterator();
		
		while(iterator.hasNext()){//域迭代
			String field=iterator.next();
			Iterator<String> rules=fieldsMap.get(field).keySet().iterator();
			Map<String, String> rulesMap=fieldsMap.get(field);
			while(rules.hasNext()){//域规则验证
				String rule=rules.next();
				Object ruleParam;
				if(JqueryMethod.EQUALTO.equals(rule)){
					ruleParam=request.getParameter(rulesMap.get(rule).replaceAll("#", ""));
				}else{
					ruleParam=rulesMap.get(rule);
				}
				Object value=request.getParameter(field);
				boolean isPassed=JqueryMethod.validate(rule, ruleParam,value);
				if(!isPassed){
					result.put(field, messagesMap.get(field).get(rule));
					break;//规则未通过结束域的验证
				}
			}
		}
		return result;
	}
	

	/**
	 * 初始一个无内容但size为1的errorMap，struts返回到输入页面
	 * @return
	 */
	public static Map<String, List<String>> initErrorMap() {
		Map<String, List<String>> errorMap=new HashMap<String, List<String>>();
		errorMap.put(null, null);
		return errorMap;
	}

}
